package com.algo.rpc.common;

import com.algo.rpc.common.Constants;
import com.algo.rpc.common.HessionSerializeUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import org.apache.log4j.Logger;

import java.util.List;

/**
 * RPC报文编码器
 */
public class RpcEncoderHandler extends MessageToMessageEncoder {

    private static final Logger logger = Logger.getLogger(RpcEncoderHandler.class);

    @Override
    protected void encode(ChannelHandlerContext ctx, Object msg, List out) throws Exception {

        byte[] messageBytes = HessionSerializeUtil.serialize(msg);

        ByteBuf buffer = Unpooled.buffer(Constants.MESSAGE_HEADER_LENGTH + messageBytes.length);
        buffer.writeInt(messageBytes.length);
        buffer.writeBytes(messageBytes);

        logger.info("rpc message encode finish, byte length is " + messageBytes.length);

        out.add(buffer);
    }

}
